package com.lagou.gateway.filter;

import com.lagou.gateway.standard.GatewayResponseDecorator;
import com.lagou.gateway.standard.formatter.ResponseBodyFormatter;
import com.lagou.gateway.standard.handler.ResponseBodyHandlers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@ConditionalOnProperty(prefix = "lagou.gateway.out.standard", name = "enable", havingValue = "true")
public class StandardResponseBodyFilter implements GlobalFilter, Ordered {

    @Autowired
    ResponseBodyFormatter responseBodyFormatter;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        GatewayResponseDecorator responseDecorator = new GatewayResponseDecorator(
                ResponseBodyHandlers.getJsonBodyHandler(responseBodyFormatter),
                ResponseBodyHandlers.getErrorHeaderBodyHandler(),
                ResponseBodyHandlers.getNormalBodyHandler(),
                exchange.getResponse());

        /**
         * post filter会在 response或者then里执行
         */
        return chain
                .filter(exchange.mutate().response(responseDecorator).build());
    }

    @Override
    public int getOrder() {
        return FilterOrder.STANDARD_RESPONSE_FILTER_ORDER;
    }
}
